<template>
  <div class="edit-page-wrap">
    <Head title="渠道企业信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="140px"
          class="edit-form-wrap"
        >
          <el-form-item label="企业名称" prop="orgName">
            <el-input
              v-model.trim="ruleForm.orgName"
              placeholder="请输入企业名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="运营商名称" prop="operatorName">
            <el-input
              v-model.trim="ruleForm.operatorName"
              placeholder="请输入运营商名称"
              maxlength="10"
              clearable
            />
          </el-form-item>
          <el-form-item label="企业注册地址" prop="address">
            <el-input
              v-model.trim="ruleForm.address"
              placeholder="请输入企业注册地址"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="code">
            <el-input
              v-model.trim="ruleForm.code"
              placeholder="请输入统一社会信用代码"
              maxlength="18"
              clearable
            />
          </el-form-item>
          <el-form-item label="归属城市" prop="cityCodes">
            <el-cascader
              ref="cityRef"
              popper-class="qc-cascader"
              v-model="ruleForm.cityCodes"
              :options="optionsS.city"
              @change="handleChangeCity"
              placeholder="请选择归属城市"
              clearable
            />
          </el-form-item>
          <el-form-item label="签约时间" prop="signTime">
            <div class="edit-date-wrap">
              <el-date-picker
                v-model="ruleForm.signTime"
                popper-class="qc-date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </div>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-line"></div>
    <Head title="其他信息">
      <template #content>
        <el-form
          ref="ruleFormOtherRef"
          :model="ruleForm"
          :rules="rules"
          label-width="140px"
          class="edit-form-wrap"
        >
          <el-form-item label="联系人" prop="contactUser">
            <el-input
              v-model.trim="ruleForm.contactUser"
              placeholder="请输入联系人"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="联系方式" prop="contactNum">
            <el-input
              v-model.trim="ruleForm.contactNum"
              placeholder="请输入联系方式"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="联系地址" prop="contactAddress">
            <el-input
              v-model.trim="ruleForm.contactAddress"
              placeholder="请输入联系地址"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="联系邮箱" prop="email">
            <el-input
              v-model.trim="ruleForm.email"
              placeholder="请输入联系邮箱"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="营业执照" prop="businessLicense">
            <QcUpload
              :valueModel="ruleForm.businessLicense"
              @on-success="handleSuccessLicense"
              @before-upload="beforeUploadLicense"
              @on-error="handleErrorLicense"
            ></QcUpload>
          </el-form-item>
          <el-form-item label="企业图标" prop="businessLogo">
            <QcUpload
              :valueModel="ruleForm.businessLogo"
              @on-success="handleSuccessLogo"
              @before-upload="beforeUploadLogo"
              tip="该图标用于平台登录欢迎页展示，只能上传jpg/jpeg/png文件，且不超过2M， （建议尺寸：266*238）"
            ></QcUpload>
          </el-form-item>
          <el-form-item label="备注说明" prop="remark">
            <el-input
              v-model.trim="ruleForm.remark"
              placeholder="请输入备注说明"
              maxlength="200"
              type="textarea"
              :rows="3"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import Head from '@/components/head/index.vue';
import QcUpload from '@/components/qcUpload/index.vue';
import { getCity, getDay } from '@/utils/utils';
import {
  addChannel,
  updateChannel,
  queryChannelDetail,
} from '@/service/apis/channel';
import { IS_EN_NUMBER_18 } from '@/utils/verify';

const route = useRoute();
const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const ruleFormOtherRef = ref<FormInstance>();

const {
  query: { id },
} = route;

let optionsS = reactive({
  city: [] as any,
});

// 获取省市
getCity().then((res: any) => {
  optionsS.city = res;
});

let ruleForm: any = reactive({
  id: '',
  orgName: '',
  operatorName: '',
  address: '',
  code: '',
  cityCodes: [] as any,
  cityCode: '',
  cityName: '',
  provinceCode: '',
  signTime: [] as any,
  signStartTime: '',
  signEndTime: '',
  contactUser: '',
  contactNum: '',
  contactAddress: '',
  email: '',
  businessLicense: '',
  businessLogo: '',
  remark: '',
});

if (id) {
  queryChannelDetail({ id: id }).then((res: any) => {
    if (res) {
      for (const key in ruleForm) {
        if (res[key]) {
          ruleForm[key] = res[key];
        }
      }
      if (res.signStartTime && res.signEndTime) {
        ruleForm.signTime = [res.signStartTime, res.signEndTime];
      }
      if (res.provinceCode && res.cityCode) {
        ruleForm.cityCodes = [res.provinceCode, res.cityCode];
      }
    }
  });
}
const errLicense = ref('');
const checkLicense = (rule: any, value: any, callback: any) => {
  if (!value) {
    if (errLicense.value === 'type') {
      callback(new Error('上传的图片格式不正确'));
    } else if (errLicense.value === 'size') {
      callback(new Error('上传的图片大于2M'));
    } else if (errLogo.value === 'error') {
      callback(new Error('上传失败'));
    }
  }
  callback();
};
const errLogo = ref('');
const checkLogo = (rule: any, value: any, callback: any) => {
  if (!value) {
    if (errLogo.value === 'type') {
      callback(new Error('上传的图片格式不正确'));
    } else if (errLogo.value === 'size') {
      callback(new Error('上传的图片大于2M'));
    }
  }
  callback();
};
const rules = reactive<FormRules>({
  orgName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  operatorName: [
    { required: true, message: '请输入运营商名称', trigger: 'blur' },
  ],
  address: [{ required: true, message: '请输入企业注册地址', trigger: 'blur' }],
  code: [
    { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
    {
      pattern: IS_EN_NUMBER_18,
      message: '请输入正确的18位统一社会信用代码',
      trigger: 'blur',
    },
  ],
  // cityCodes: [{ required: true, message: '请选择归属城市', trigger: 'change' }],
  // signTime: [{ required: true, message: '请选择签约时间', trigger: 'change' }],
  contactUser: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactNum: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  contactAddress: [
    { required: true, message: '请输入联系地址', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的联系邮箱',
      trigger: 'blur',
    },
  ],
  businessLicense: [{ validator: checkLicense, trigger: 'change' }],
  businessLogo: [{ validator: checkLogo, trigger: 'change' }],
});

const cityRef = ref();
const handleChangeCity = (e: any) => {
  if (e) {
    ruleForm.cityCodes = e;
    ruleForm.cityCode = e[1];
    ruleForm.provinceCode = e[0];
    const node = cityRef.value.getCheckedNodes()[0];
    ruleForm.cityName = node.pathLabels[1];
  } else {
    ruleForm.cityCodes = '';
    ruleForm.cityCode = '';
    ruleForm.provinceCode = '';
    ruleForm.cityName = '';
  }
};

//营业执照
const handleSuccessLicense = (val: any) => {
  ruleForm.businessLicense = val;
  ruleFormOtherRef?.value?.validateField('businessLicense');
};
const handleErrorLicense = () => {
  errLicense.value = 'error';
  ruleFormOtherRef?.value?.validateField('businessLicense');
};
const beforeUploadLicense = (type: string) => {
  errLicense.value = type;
  if (type) {
    ruleFormOtherRef?.value?.validateField('businessLicense');
  }
};

//企业图标
const handleSuccessLogo = (val: any) => {
  ruleForm.businessLogo = val;
};
const beforeUploadLogo = (type: string) => {
  errLogo.value = type;
  ruleFormOtherRef?.value?.validateField('businessLogo');
};

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value || !ruleFormOtherRef.value) return;
  errLicense.value = '';
  errLogo.value = '';
  try {
    await Promise.all([
      ruleFormRef.value.validate(),
      ruleFormOtherRef.value.validate(),
    ]);
  } catch (fields: any) {
    for (const key in ruleForm) {
      if (fields[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleFormOtherRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  ruleForm.signStartTime = '';
  ruleForm.signEndTime = '';
  if (ruleForm.signTime?.length > 0) {
    ruleForm.signStartTime = getDay(ruleForm.signTime[0]);
    ruleForm.signEndTime = getDay(ruleForm.signTime[1]);
  }

  ruleForm.code = ruleForm.code.toLocaleUpperCase();
  console.log('ruleForm---', ruleForm);
  if (id) {
    updateChannel(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    addChannel(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>